﻿using CommonTools;
using Newtonsoft.Json;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace shop.Bll.cost
{
    public class PostQtyPriceBll : IPageBll<PostQtyPrice>
    {
        public string Title => "物流计件资费";

        public bool EnableEditOnList => true;

        //public bool EnableCreateOnList => true;

        public bool RefreshOnOpen => true;

        public Action<int> TurnPage { set; get; }
        public PostQtyPrice CopyItem(PostQtyPrice item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.Id = 0;
            newItem.isdel = false;

            return newItem;
        }

        public PostQtyPrice CreateItem()
        {
            return new PostQtyPrice() { isdel = false, FUser = UserBll.CurrentUser.Name, FTime = DateTime.Now, };
        }

        public async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<PostQtyPrice>()
                .Where(a => a.Id == id && a.isdel == false)
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();

            await DB.FSql.Insert(new CLogs()
            {
                DocName = nameof(PostQtyPrice),
                Computer = UserBll.CurrentUser.ComputerInfo,
                Zdr = UserBll.CurrentUser.Name,
                DocId = id.ToString(),
                DocAction = "删除",
            })
                .ExecuteAffrowsAsync();

            return new Result(true);
        }


        public async Task<Result<int>> EditCell(string dataPropertyName, object value, PostQtyPrice data)
        {
            if (data.Id == 0)
            {
                data.FTime = await DB.FSql.GetTimeAsync();
                data.FUser = UserBll.CurrentUser.Name;
                data.isdel = false;
                data.EndDate = new DateTime(2099, 1, 1);

                var nid = await DB.FSql.Insert(data)
                    .ExecuteIdentityAsync();

                data.Id = (int)nid;

            }

            var dbRes = await DB.FSql.Update<PostQtyPrice>()
                .Where(a => a.Id == data.Id && a.isdel == false)
                .SetDto(new Dictionary<string, object> { [dataPropertyName] = value })
                .ExecuteAffrowsAsync();

            return new Result<int>(true, null, data.Id);
        }

        public IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
           {
                new DeclareColumn(nameof(PostQtyPrice.Id),"Id"){ Visible= false},
                new DeclareColumn(nameof(PostQtyPrice.BeginDate),"起始日期"){ ValueType= typeof(DateTime), Format="yyyy-MM-dd"},
                new DeclareColumn(nameof(PostQtyPrice.EndDate),"截止日期"){ ValueType= typeof(DateTime), Format="yyyy-MM-dd"},
                new DeclareColumn(nameof(PostQtyPrice.logistics_name),"物流公司"),
                new DeclareColumn(nameof(PostQtyPrice.goods_no),"货品编号"){ Width=270},
                new DeclareColumn(nameof(PostQtyPrice.province),"省份"),
                new DeclareColumn(nameof(PostQtyPrice.PriceByQty),"按件计费单价"){ValueType=typeof(decimal)},
                new DeclareColumn(nameof(PostQtyPrice.FUser),"制单人"),
            };

        }

        public async Task<PostQtyPrice> GetItem(int id)
        {
            var list = await DB.FSql.Select<PostQtyPrice>()
                .Where(a => a.isdel == false && a.Id == id)
                .ToOneAsync();
            return list;
        }



        #region 查询参数

        private DateTime? _begin;
        private DateTime? _end;
        private string _logi;
        private string _prov;
        private string _spec_no;


        #endregion

        /// <summary> 查询ui </summary>
        public virtual ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                .Add<DateTime?>(ControlEnum.gtDatePicker, "起始日期", c => _begin = c)
                .Add<DateTime?>(ControlEnum.gtDatePicker, "截止日期", c => _end = c)
                .AddGuanTextBox("省份", c => _prov = c)
                .AddGuanTextBox("商家编码", c => _spec_no= c)
                .AddGuanTextBox("物流公司", c => _logi = c)
                .AddQueryButton("查询");
        }


        /// <summary> 查询 </summary>
        public async Task<PageQueryResult<PostQtyPrice>> QueryPage(DocFilterParameter queryPara)
        {
            _end = _end.LastTimeOfDay();

            var list = await DB.FSql.Select<PostQtyPrice>()
                .Where(a => a.isdel == false)
                .WhereIf(_begin != null, a => a.BeginDate <= _begin.Value.Date && a.EndDate >= _begin.Value.Date)
                .WhereIf(_end != null, a => a.BeginDate <= _end.Value.Date && a.EndDate >= _end.Value.Date)
                .WhereIf(!string.IsNullOrEmpty(_logi), a => a.logistics_name.Contains(_logi))
                .WhereIf(!string.IsNullOrEmpty(_prov), a => a.province.Contains(_prov))
                .WhereIf(!string.IsNullOrEmpty(_spec_no), a => a.goods_no.Contains(_spec_no))
                .Page(queryPara.PageNo, queryPara.PageSize)
                .OrderByDescending(a => a.BeginDate)
                .OrderByDescending(a => a.Id)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<PostQtyPrice>(true, null, list, c);
        }



        public async Task<Result> SaveItem(PostQtyPrice item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }


            string err = string.Empty;
            //if (string.IsNullOrEmpty(item.shop_name))
            //{
            //    err += "店铺名称不能为空!";
            //}
            if (string.IsNullOrEmpty(item.province))
            {
                err += "省份不能为空";
            }

            if (string.IsNullOrEmpty(item.logistics_name))
            {
                err += "物流公司不能为空";
            }
            if (item.BeginDate == null)
            {
                err += "起始日期不能为空";
            }

            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }

            item.isdel = false;
            item.FTime = await DB.FSql.GetTimeAsync();
            item.FUser = UserBll.CurrentUser.Name;

            if (item.Id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.Id = (int)id;
            }
            else
            {
                await DB.FSql.Update<PostQtyPrice>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);

        }


        public async Task<Result> SaveItem(IEnumerable<PostQtyPrice> items)
        {
            if (items == null)
            {
                return new Result(false, "系统错误");
            }


            var time = await DB.FSql.GetTimeAsync();

            foreach (var item in items)
            {
                item.isdel = false;
                item.FTime = time;
                item.FUser = UserBll.CurrentUser.Name;
                
                item.goods_no = (item.goods_no ?? string.Empty).Trim();
                item.logistics_name = (item.logistics_name ?? string.Empty).Trim();
            }

            await DB.FSql.Insert(items).ExecuteAffrowsAsync();

            return new Result(true);

        }


    }
}
